from typing import List, Dict, Any, Optional

from qwen3_agent_function_calling.tools.TestTool import TestTool
from qwen3_agent_function_calling.tools.Tool import Tool
from qwen3_agent_function_calling.tools.CalculatorTool import CalculatorTool
from qwen3_agent_function_calling.tools.WeatherTool import WeatherTool
from qwen3_agent_function_calling.tools.DatetimeTool import DatetimeTool

class ToolManager:
    """工具管理器，负责管理和执行所有工具"""

    def __init__(self):
        self.tools: Dict[str, Tool] = {}
        self._register_default_tools()

    def _register_default_tools(self) -> None:
        """注册默认工具"""
        default_tools = [
            CalculatorTool(),
            WeatherTool(),
            DatetimeTool(),
            TestTool()
        ]
        for tool in default_tools:
            self.register_tool(tool)

    def register_tool(self, tool: Tool) -> None:
        """注册新工具"""
        tool_name = tool.get_name()
        self.tools[tool_name] = tool
        print(f"已注册工具: {tool_name}")

    def get_tool_definitions(self) -> List[Dict[str, Any]]:
        """获取所有工具的定义"""
        return [tool.to_dict() for tool in self.tools.values()]

    def execute_tool(self, tool_name: str, arguments: Dict[str, Any]) -> str:
        """执行指定工具"""
        if tool_name not in self.tools:
            return f"错误：未知工具 '{tool_name}'"

        try:
            return self.tools[tool_name].execute(arguments)
        except Exception as e:
            return f"工具执行错误：{str(e)}"
